package com.unionpay.async;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.unionpay.config.Config;
import com.unionpay.db.TblDailytxid;
import com.unionpay.db.TblTransaction;
import com.unionpay.rpc.Data;
import com.unionpay.rpc.DataStr;
import com.unionpay.rpc.Rpc;
import com.unionpay.rpc.RpcMethod;
import com.unionpay.util.SHA1;

/**
 * 定时统计任务
 * 
 * @author liuzy
 * @since 2016年4月29日
 */
public class TimerTask {
	private static Logger logger = Logger.getLogger(TimerTask.class);
	public static final SimpleDateFormat hmSdf = new SimpleDateFormat("HH:mm:ss");
	public static final SimpleDateFormat ymdSdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 上一次执行任务的时间
	 */
	private static volatile String lastTime = null;

	/**
	 * 运行标记
	 */
	private static volatile boolean isRun = true;

	/**
	 * 任务开始
	 */
	public static void start(final String TIMER_TIME) {
		Thread timerTaskThread = new Thread(new Runnable() {
			@Override
			public void run() {
				while (isRun) {
					try {
						if (hmSdf.format(new Date()).startsWith(TIMER_TIME)) {
							// 昨天的日期
							Calendar calendar = Calendar.getInstance();
							calendar.add(Calendar.DATE, -1);
							String yesterday = ymdSdf.format(calendar.getTime());
							if (yesterday.equals(lastTime)) {
								Thread.sleep(3 * 1000);
								continue;
							} else {
								lastTime = yesterday;
							}
							
							logger.info("TimerTask start...");
							System.out.println("date:" + yesterday);
							
							// 查询交易
							List<String> trans = TblTransaction.findByDate(yesterday);
							System.out.println("trans:" + trans.size());
							StringBuffer sb = new StringBuffer();
							for (String tran : trans) {
								sb.append(tran);
							}
							
							// 计算哈希
							String hash = SHA1.encode(sb.toString());
							System.out.println("hash:" + hash);
							
							// 开始RPC
							RpcMethod transMethod = new RpcMethod(Rpc.ETH_SENDTRANSACTION);
							transMethod.addParams(Config.PUBLIC_USER, hash);
							Data dd = Rpc.request(Config.PUBLIC_RPC, transMethod);
							if (dd instanceof DataStr) {
								String txid = ((DataStr) dd).getResult();
								if (TblDailytxid.find(yesterday) == null) {
									TblDailytxid.save(yesterday, hash, txid);
								} else {
									TblDailytxid.update(yesterday, hash, txid);
								}
							} else if (dd != null) {
								System.out.println("rpc error:" + dd.getError().getMessage());
							}
						} else {
							Thread.sleep(3 * 1000);
						}
					} catch (Exception e) {
						e.printStackTrace();
						try {
							Thread.sleep(60 * 1000);//出现异常，休息1分种后继续
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		});
		timerTaskThread.setName("TimerTask-timerTaskThread-0");
		timerTaskThread.start();
	}

	public static void destroy() {
		isRun = false;
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
